<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Auth;
use App\Models\Admin\AdminUser;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Validator;
use Carbon\Carbon;

/**
 * 【登录，登出实现 注册没有实现】
 */
class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
     */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    //登录成功重定向路径
    protected $redirectTo = '/admin';

    protected $username;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //登录成功重定向路径
        $this->redirectTo = config('inventory.base.route_prefix') . '/' . config('inventory.base.loginSuccessRedirectTo');
        $this->middleware('guest:' . config('inventory.base.guard'), ['except' => 'logout']);
    }

    /**
     * 复写登陆鉴权
     */
    public function login(Request $request)
    {
        //进行一个鉴权
        $validator = $this->validateLogin($request->input());
        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }
        // 后台通过用户名或手机号登录
        if (Auth::guard(config('inventory.base.guard'))->attempt(['name' => $request->username, 'password' => $request->password], 1)) {
	    // 更新登录时间
            AdminUser::where(['name' => $request->username])->update(['logined_at' => Carbon::now()]);
            // 写入日志中
            event(new \App\Events\LoginEvent(AdminUser::where(['name' => $request->username])->select(['id', 'name', 'real_name', 'phone'])->first()));
            return redirect()->to($this->redirectTo)->with('success', '登录成功！');
        } else if (Auth::guard(config('inventory.base.guard'))->attempt(['phone' => $request->username, 'password' => $request->password], 1)) {
            // 更新登录时间
            AdminUser::where(['phone' => $request->username])->update(['logined_at' => Carbon::now()]);
            // 写入日志中
            event(new \App\Events\LoginEvent(AdminUser::where(['phone' => $request->username])->select(['id', 'name', 'real_name', 'phone'])->first()));

            return redirect()->to($this->redirectTo)->with('success', '登录成功！');
            // Redirect::guest() 在重定向时会将当前url保存到session中，这样可以在登陆以后，使用 Redirect::intended() 方法跳转到之前的页面继续业务。
            // Redirect::intended('/') 这个方法的意思是跳转到之前的页面，如果像上面那样使用了 Redirect::guest()方法，那么intended这里就会跳转到那时候的url，而它的参数只是一个默认值，再没有记录历史url的时候会跳转到’/’。
            // return back()->withErrors('文件格式只能为xls, xlsx, csv')->withInput();
            // return back()->with(['file' => '文件格式只能为xls, xlsx, csv'])->withInput();with()函数中的status，理解为key。用session取这个key就可以了
        }
        return back()->withErrors('账号或密码错误')->withInput();
    }

    //登录页面验证
    protected function validateLogin(array $data)
    {
        return Validator::make($data, [
            'username' => 'required',
            'password' => 'required',
        ], [
            'required' => ':attribute 为必填项',
            'min'      => ':attribute 长度不符合要求',
        ], [
            'account_number' => '账号',
            'password'       => '密码',
        ]);
    }

    /**
     * 登录名或邮件，没用到
     */
    // public function loginNameOrEmail(Request $request)
    // {
    //     $field = filter_var($request->input('email'), FILTER_VALIDATE_EMAIL) ? 'email' : 'name';
    //     $request->merge([$field => $request->input('email')]);
    //     $this->username = $field;

    //     return $this->login($request);
    // }

    /**
     * 重写登录视图页面
     */
    public function showLoginForm()
    {
        return view('admin.auth.login');
    }
    /**
     * 自定义认证驱动
     */
    protected function guard()
    {
        return auth()->guard(config('inventory.base.guard'));
    }

    /**
     * 登出
     * Log the user out of the application.
     *
     * @param  Request  $request
     * @return \Illuminate\Http\Response
     */
    public function logout()
    {
        if (Auth::guard(config('inventory.base.guard'))->user()) {
            // 写入日志中
            event(new \App\Events\LogoutEvent(Auth::guard(config('inventory.base.guard'))->user()));
            $this->guard(config('inventory.base.guard'))->logout();
        }

        request()->session()->flush();

        request()->session()->regenerate();

        return redirect(config('inventory.base.route_prefix') . '/login');
    }

}
